package com.job.learn.cuiyt.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.job.learn.cuiyt.job.FileBackUpJob;
import com.job.learn.cuiyt.job.PersonJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author: cuiyutian1
 * @date: 2021/12/26 13:37
 * @description:
 */
@Configuration
public class SchedulerConfig {

    @Resource
    private FileBackUpJob fileBackUpJob;


    @Resource
    private PersonJob personJob;

    @Resource
    private CoordinatorRegistryCenter coordinatorRegistryCenter;


    private LiteJobConfiguration create(final Class<? extends SimpleJob> jobClass,
                                        final String cron,
                                        final int sharedCount,
                                        final String params){
        JobCoreConfiguration.Builder builder = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, sharedCount);

        if(StringUtils.isNotBlank(params)){
            builder.shardingItemParameters(params);
        }

        JobCoreConfiguration build = builder.build();
        SimpleJobConfiguration configuration = new SimpleJobConfiguration(build, jobClass.getCanonicalName());
        return LiteJobConfiguration.newBuilder(configuration).overwrite(true).build();
    }


    @Bean(initMethod = "init")
    SpringJobScheduler springJobScheduler(){
        SpringJobScheduler jobScheduler = new SpringJobScheduler(personJob, coordinatorRegistryCenter,
                create(personJob.getClass(), "0/3 * * * * ?", 2, "0=0,1=1"));
        return jobScheduler;
    }

}
